package app

import (
	"context"
	"github.com/kataras/iris/v12"
	"lib/api/http"
	"lib/exception"
	"sync"
	"time"
)

var once sync.Once
var serverInstance *applicationServer

type applicationServer struct {
	irisApp *iris.Application
}

func initialization() {
	once.Do(func() {
		serverInstance = &applicationServer{
			irisApp: iris.New(),
		}
	})
}

func (a *applicationServer) Instance() *iris.Application {
	return a.irisApp
}

func (a *applicationServer) Startup(listenAddress string) exception.Exception {
	startupErr := serverInstance.irisApp.Listen(listenAddress)
	if startupErr != nil {
		return startupErr
	}
	return nil
}

func (a *applicationServer) Shutdown() exception.Exception {
	timeout := time.Second * 10
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	shutdownErr := serverInstance.irisApp.Shutdown(ctx)
	if shutdownErr != nil {
		return shutdownErr
	}
	return nil
}

func Instance() http.ApplicationServer {
	initialization()
	return serverInstance
}

func Startup(listenAddress string) exception.Exception {
	initialization()
	return serverInstance.Startup(listenAddress)
}

func Shutdown() exception.Exception {
	return serverInstance.Shutdown()
}
